package hotel.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import hotel.action.ForwardActionTo;
import hotel.form.RequestForm;
import hotel.model.IUser;
import hotel.service.RequestService;
import hotel.service.ServiceManager;
/**
 * This class create a new request
 * @author Alex
 *
 */
public class RequestAction extends Action
{
	private static final Logger logger = Logger.getLogger(RequestAction.class);
	private static final String REQUEST_ERROR = "Error in RequestAction:";
	@Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception 
    {
		String mapper = ForwardActionTo.ERROR;
		
		try
		{
		    RequestForm requestForm = (RequestForm)form;
		    ActionMessages messages = new ActionMessages();
		    HttpSession session = request.getSession(true);
		    IUser user = (IUser)session.getAttribute("user");
			if (requestForm != null) 
		     {
		    	RequestService requestService = ServiceManager.getDefault().getRequestService();
		        requestService.insert(
		        		requestForm.getRoomClass(),
						 requestForm.getBeds(),
						 user.getName(),
						 user.getSurname(),
						 user.getUsername());
		        mapper = ForwardActionTo.SUCCESS;   
		        messages.add("addRequest_success", new ActionMessage("message.request.add.success"));

		        messages.add("request_id", new ActionMessage("message.request.add.success.id", requestService.getByUsername(user.getUsername()).getId()));
		        saveMessages(request, messages);
		     }
		}
		catch(NullPointerException e)
		{
			logger.error(REQUEST_ERROR + e);
		}
		
		return mapping.findForward(mapper);
    }
}